package cn.com.chengmandian.core.lot.utils;

import cn.hutool.core.net.NetUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.qpid.jms.JmsConnection;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.jms.ConnectionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;

public class AmqpUtil {
    /**
     * 计算签名，password组装方法，请参见AMQP客户端接入说明文档。
     */
    public static String doSign(String toSignString, String secret, String signMethod) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
        Mac mac = Mac.getInstance(signMethod);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }

    public static Context initContext(String host) throws Exception {
        String connectionUrl = "failover:(amqps://" + host + ":5671?amqp.idleTimeout=80000)?failover.reconnectDelay=30";

        Hashtable<String, String> hashtable = new Hashtable<>();
        hashtable.put("connectionfactory.SBCF", connectionUrl);
        hashtable.put("queue.QUEUE", "default");
        hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        return new InitialContext(hashtable);
    }


    public static JmsConnection initJmsConnection(Context context, String iotInstanceId, String accessKeyId, String accessKeySecret, String consumerGroupId) throws Exception {
        ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");
        //参数说明，请参见AMQP客户端接入说明文档。
        long timeStamp = System.currentTimeMillis();
        //签名方法：支持hmacmd5、hmacsha1和hmacsha256。
        String signMethod = "hmacsha1";
        //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。
        String userName = "xh-" + NetUtil.localIps().stream().findFirst() + "|authMode=aksign"
                + ",signMethod=" + signMethod
                + ",timestamp=" + timeStamp
                + ",authId=" + accessKeyId
                + ",iotInstanceId=" + iotInstanceId
                + ",consumerGroupId=" + consumerGroupId
                + "|";
        //计算签名，password组装方法，请参见AMQP客户端接入说明文档。
        String signContent = "authId=" + accessKeyId + "&timestamp=" + timeStamp;
        return (JmsConnection)cf.createConnection(userName, AmqpUtil.doSign(signContent, accessKeySecret, signMethod));
    }
}
